
import React from 'react';
import { 
  NativeModules, 
  View, 
  StyleSheet, 
  Text, 
  TextInput, 
  Platform, 
  Picker, 
  Dimensions, 
  KeyboardAvoidingView,
  TouchableOpacity,
  ScrollView
} from 'react-native';
import BackgroundImage from '../../config/BackgroundImage';
import TextInput2 from '../../components/TextInput2';
import Divider from '../../components/divider/Divider';
import colors from '../../config/colors';
import Button from '../../components/Button';
import BlurView from 'react-native-blur';
import { getDeviceInfo } from '../../utils/DeviceInfo';
import ModalDropdown from 'react-native-modal-dropdown';
import NavigationUtil from '../../utils/NavigationUtil';
import store from 'react-native-simple-store';
const AESData = require('../../data/AE01.json');
// import {RSA, RSAKeychain} from 'react-native-rsa-native';
// import RSA from 'react-native-rsa-util';
import { getJson } from '../../utils/JsonUtil';
import ToastUtil from '../../utils/ToastUtil';
import * as types from '../../constants/ActionTypes';
import LoadingSpinnerOverlay from '../../components/LoadingSpinnerOverlay';

const _ = require('lodash');
const ReactAES = NativeModules.ReactAES;
const maxHeight = Dimensions.get('window').height;
const maxWidth = Dimensions.get('window').width;

const loginBgImage = require("../../img/loginBg.jpg");

class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      passsword: '',
      siteName: '',
      siteList: []
    }

    this.isLoadSites = false;
    this.isSubmiting = false;
    this.username = ''
    this.data = {};
    this.onUserChange = this.onUserChange.bind(this);
    this.onValueChange = this.onValueChange.bind(this);
    this.onPasswordChange = this.onPasswordChange.bind(this);
    this.onLoginPress = this.onLoginPress.bind(this);
    this._navToPrivacyPage = this._navToPrivacyPage.bind(this);
    this.onSelect = this.onSelect.bind(this);
  };

  componentWillReceiveProps(nextProps) {
    // console.log('nextProps', nextProps)
    if (this.isSubmiting === true 
    && nextProps.user.type === types.RECEIVE_LOGIN_DATA) {
      if (nextProps.user.authData) {
        const {key, iv} = AESData;
        ReactAES.decrypt(nextProps.user.authData, key, iv)
        .then((decrypted) => {
          if (decrypted) {
            const authData = getJson(decrypted);
            store.save('token', authData['token'])
            .then(() => store.save('authData', nextProps.user.authData))
            .then(() => store.save('site_id', this.data['site_id']))
            .then(() => {
              this.modalLoadingSpinnerOverLayHide({animationEnd: () => {
                NavigationUtil.reset(this.props.navigation, 'Home')
              }});
            })
          }
          this.isSubmiting = false;
        }).catch(e => {
          this.modalLoadingSpinnerOverLayHide({animationEnd: () => {
            requestAnimationFrame(() => ToastUtil.showShort('登陆失败!'))
          }});
          this.isSubmiting = false;
        });
      } else {
        this.modalLoadingSpinnerOverLayHide({animationEnd: () => {
          requestAnimationFrame(() => ToastUtil.showShort(nextProps.user.errorMessage))
        }});
        this.isSubmiting = false;
      }
    }
  }

  _navToPrivacyPage () {
    const { navigate } = this.props.navigation;
    navigate('scrm', {
     article: {
      url: 'https://scrm.91mycloud.com/scrm/privacy.html',
      title: '隐私政策'
     } 
    })
  }

  modalLoadingSpinnerOverLayHide (options) {
    setTimeout(() => this._modalLoadingSpinnerOverLay.hide(options), 1200)
  }

  isPhone (str) {
    var re = new RegExp(/^((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)$/);
    return re.test(str);
  }

  onUserChange (ev) {
    if (ev && ev.nativeEvent) {
      const phone = ev.nativeEvent.text;
      this.data['username'] = phone;
      this.utid && clearTimeout(this.utid);
      if (this.isPhone(phone)) {
        this.utid = setTimeout(() => {
          this.loadSites(phone)
        }, 1200)
      }
    }
  };

  onPasswordChange (ev) {
    if (ev && ev.nativeEvent) {
      const password = ev.nativeEvent.text;
      this.data['password'] = password;
    }
  };

  loadSites (username) {
    const { userActions } = this.props;
    userActions.requestUserSites(username)
    this.isLoadSites = true;
  }

  componentWillUnmount() {
    this.isLoadSites = false;
    this.isSubmiting = false;
  }

  componentDidMount() {
  }

  onValueChange () {
  };

  onLoginPress () {
    if (this.isSubmiting) return ToastUtil.showShort('提交中，请勿着急');
    
    if (!this.data['username']) return ToastUtil.showShort('请填写手机号码');
    if (!this.data['password']) return ToastUtil.showShort('请填写密码!');
    if (!this.data['site_id']) return ToastUtil.showShort('必须选择一个站点!');
    if (!this.isPhone(this.data['username'])) return ToastUtil.showShort('手机号码不正确！');

    this.isSubmiting = true;
    this._modalLoadingSpinnerOverLay.show();

    const { userActions } = this.props;
    const {key, iv, chiper} = AESData;
    const deviceInfo = getDeviceInfo();
    
    let loginData = Object.assign({
      site_id: this.data['site_id'],
      mobile: this.data['username'],
      encrypted_type: 0
    }, deviceInfo);

    let encryptMethod;
    if (Platform.OS === 'android') {
      const RSAUtil = require('react-native-rsa-native') //android 25
      encryptMethod = RSAUtil.RSA.encrypt;
    } else {
      const RSAUtil = require('react-native-rsa-util') // ios 9 +
      encryptMethod = RSAUtil.encryptStringWithPublicKey;
    }
    
    ReactAES.decrypt(chiper, key, iv).then((decrypted) => {
      return encryptMethod(JSON.stringify({
          'unique_id': deviceInfo.unique_id,
          'password': this.data['password']
      }), decrypted).then((encrypted) => {
          loginData = Object.assign({}, loginData, { encrypted_text: encrypted })
          delete loginData['unique_id'];
          userActions.requestLogin(loginData, this.props);
      })
   })
  }

  onSelect (index) {
    const { sites } = this.props.user;
    this.data['site_id'] = sites[index]['site_id'];
  }

  renderSitePicker () {
    const { sites } = this.props.user;
    // if (!sites || sites.length === 0) {
    //   return ;
    // }
    let siteNameList = []
    _.map(sites, site => siteNameList.push(site.site_name));

    return (
      <View style={styles.sitePickerStyle}>
        <View style={[styles.usernameTitleStyle]}>
          <Text style={[styles.loginTextStyle]}>站点</Text>
        </View>
        <ModalDropdown 
          onSelect={this.onSelect}
          defaultValue='请选择站点'
          animated={false}
          keyboardShouldPersistTaps='always'
          style={styles.pickerStyle}
          textStyle={styles.pickerTextStyle}
          dropdownStyle={styles.dropdownStyle}
          options={siteNameList}
        />
      </View>
    )
  }

  render () {
    return (
      <BackgroundImage
      resizeMode="cover"
      style={styles.imageStyle}
      source={loginBgImage}
      >
        <View style={styles.shadowCoverStyle}>
        <ScrollView style={styles.scrollStyle}>
          <KeyboardAvoidingView 
          style={styles.containerStyle}
          behavior="position">
            <View style={styles.loginFormWrapperStyle}>
              <View style={styles.sloganWrapperStyle}>
                <Text style={[styles.loginTextStyle, styles.sloganTextStyle]}>您好!</Text>
                <Text style={[styles.loginTextStyle, styles.sloganTextStyle]}>欢迎使用CRM</Text>
              </View>
              <View style={[styles.usernameTitleStyle]}>
                <Text style={[styles.loginTextStyle]}>手机号码</Text>
              </View>
              <View style={styles.textInputWrapperStyle}>
                <TextInput2
                  multiline={false}
                  underlineColorAndroid='transparent'
                  placeholderTextColor={colors.grey6}
                  placeholderStyle={styles.placeholderStyle}
                  onChange={this.onUserChange}
                  style={styles.textInpuStyle}
                  text={this.username}
                  placeholder='请输入手机号'
                  />
              </View>
              <Divider dividerStyle={styles.dividerStyle} />
              <View style={[styles.usernameTitleStyle]}>
                <Text style={[styles.loginTextStyle]}>密码</Text>
              </View>
              <View style={styles.textInputWrapperStyle}>
                <TextInput2
                  secureTextEntry={true}
                  underlineColorAndroid='transparent'
                  placeholderTextColor={colors.grey6}
                  style={styles.textInpuStyle}
                  text={this.state.username}
                  onChange={this.onPasswordChange}
                  placeholder='密码'
                  selectionColor={"white"}
                  />
              </View>
              <Divider dividerStyle={styles.dividerStyle} />
              { this.renderSitePicker()} 
              <Button onPress={this.onLoginPress} style={styles.loginBtnStyle} text='登陆' />
            </View>
            <View style={styles.privacyWrapperStyle}>
              <Text style={styles.privacyStyle}>登陆即代表阅读并同意</Text><TouchableOpacity
              style={styles.privacyStyle} 
              onPress={this._navToPrivacyPage}><Text style={styles.termsLinkStyle}>隐私政策</Text></TouchableOpacity>
            </View>
          </KeyboardAvoidingView>
        </ScrollView>
        <LoadingSpinnerOverlay
              ref={ component => this._modalLoadingSpinnerOverLay = component }/>
        </View>
      </BackgroundImage>
    )
  }
}

const styles = StyleSheet.create({
  containerStyle: {
  },
  shadowCoverStyle: {
    opacity: 0.6,
    backgroundColor: 'black',
    flex: 1
  },
  loginFormWrapperStyle: {
    paddingLeft: 30,
    paddingRight: 30,
    paddingTop: 150
  },
  imageStyle: {
    borderColor: colors.blue4,
    borderRadius: 2,
    flex: 1,
    alignItems: 'stretch'
  },
  sloganWrapperStyle: {
  },
  usernameTitleStyle: {
    paddingTop: 10,
    paddingBottom: 10,
    
  },
  sloganTextStyle: {
    paddingTop: 2,
    paddingBottom: 2,
    fontSize: 18,
    fontWeight: 'bold'
  },
  loginTextStyle: {
    color: 'white',
    fontSize: 12
  },
  textInputWrapperStyle: {
    paddingTop: 2,
    paddingBottom: 2
  },
  textInpuStyle: {
    borderBottomWidth: 0,
    fontSize: 13,
    height: 30,
    color: 'white',
    textAlign: 'left',
    padding: 0,
    paddingBottom: 4,
    ...Platform.select({
      ios: {
        marginBottom: 6
      },
      android: {
        margin: 0
      }
    })
  },
  scrollStyle: {
    flex: 1
  },
  placeholderStyle: {
    color: '#ffffff'
  },
  dividerStyle: {
    height: 0.5,
    backgroundColor: '#eaeaea'
  },
  loginBtnStyle: {
    borderWidth: 1,
    borderColor: 'white',
    color: 'white',
    padding: 10,
    flexDirection: 'row',
    borderRadius: 2,
    textAlign: 'center'
  },
  loginTextStyle: {
    color: 'white',
  },
  pickItemStyle: {
    color: 'white'
  },
  pickerStyle: {
    borderWidth: 1,
    borderColor: 'white',
    width: 130,
    marginTop: 8,
    marginBottom: 10,
    padding: 10
  },
  pickerTextStyle: {
    color: 'white'
  },
  dropdownStyle: {
    borderWidth: 1,
    borderColor: 'white',
    marginTop: 10,
    width: 130,
    marginLeft: -10
  },
  privacyWrapperStyle: {
    flex: 1,
    marginTop: 15,
    flexDirection: 'row',
    justifyContent: 'center'
  },
  privacyStyle: {
    color: 'white',
    fontSize: 12,
    lineHeight: 12
    // fontWeight: 'bold'
  },
  termsLinkStyle: {
    color: colors.blue4,
    fontWeight: 'bold',
    fontSize: 12,
    lineHeight: 12
  },
  sitePickerStyle: {
    marginBottom: 20
  },
  privacyPressViewStyle: {
    width: 58,
    height: 11
  }
})

export default Login;